<template>
  <div>
    <el-upload
      class="avatar-uploader"
      :action="baseUrl"
      :show-file-list="false"
      :on-success="onSuccess"
      :before-upload="beforeUpload">
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>

<script>
import request from '@/utils/request'
export default {
  components: {},
  props: {
    url:{
      type:String,
      default:''
    }
  },
  
  data() {
    return {
      baseUrl:request.defaults.baseURL + '/sys/uploadFile',
      photoDialog:false,//预览图片弹框，
      dialogImageUrl:'',//预览图片地址
      imageUrl:'',
      fileList: []
    };
  },
  watch: {
    url:{
      handler(newVal, oldVal) {
        if(newVal){
          this.imageUrl=newVal
        }
      },
      // deep: true,
      immediate: true,
    }
  },
  computed: {},
  created() {
    // if(this.url){
    //   this.imageUrl=this.url
    // }
  },
  methods: {
    // 案例题图片预览
    handlerPreview(file) {
      this.dialogImageUrl = file.url;
      this.photoDialog = true;
    },
    // 上传成功
    onSuccess( response, file, fileList) {
      if(response.code){
        this.imageUrl = response.data;
      }
      this.$emit('success',response.data)
    },
    onRemove(file, fileList) {
      this.fileList = fileList;
      this.$emit('success',fileList,this.index)
    },
    onExceed(files, fileList) {
      this.$message.warning(`只能上传 ${this.limit} 个文件`);
    },
    // 限制文件上传类型
    beforeUpload(file) {
      let imgArr = ['image/png','image/jpg','image/jpeg','image/gif'];
      const isJPG = file.type ;
      if(imgArr.indexOf(isJPG) == -1){
        this.$message.error('只能上传图片格式!');
        return false
      }
      const isLt2M = file.size / 1024 / 1024 < 20;

      if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 20MB!');
      }
      return isJPG && isLt2M;
    },

  }
};
</script>

<style lang='scss' scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 108px;
  height: 108px;
  line-height: 108px;
  text-align: center;
  border: 1px solid #ededed;
  border-radius: 6px;
}
.avatar {
  width: 108px;
  height: 108px;
  display: block;
  border: 1px solid #ededed;
  border-radius: 6px;
}
</style>